package com.tangsm.spring.boot.deferred.result.controller;

import com.tangsm.spring.boot.deferred.result.service.TLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Tlog 轻量级的分布式日志标记追踪控制器
 *
 * @author tangsm
 */
@RequestMapping("/log")
@RestController
public class TLogController {
    private static final Logger log = LoggerFactory.getLogger(TLogController.class);

    @Autowired
    private TLogService tLogService;

    /**
     * 打招呼
     */
    @GetMapping("/hi")
    public String sayHello() {
        log.info("sayHello 开始");

        // 打招呼
        String hello = tLogService.sayHello();
        log.info(hello);

        // 异步任务
        Future<String> future = tLogService.doTask();

        while (true) {
            if (future.isDone()) {
                log.info("异步任务完成");
                break;
            }
        }
        try {
            String s = future.get();
            log.info("异步任务结果：{}", s);
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步任务异常", e);
        }

        log.info("sayHello 完成");
        return hello;
    }

}
